<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      p {
        height: 400px;
        border: solid;
        font-size: 3rem;
      }
      #boxTop {
        width: 100px;
        height: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 2rem;
        font-weight: bold;
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: yellowgreen;
        color: white;
        cursor: pointer;
      }

      #boxTop:hover {
        background: rgb(101, 135, 33);
      }
    </style>
  </head>
  <body>
    <div id="boxTop" style="display: none">TOP</div>
    <div id="box">
      <p>
        p1

        <img
          src="./imgs/loading.gif"
          data-src="./imgs/1.jpg"
          height="200px"
          alt=""
        />
      </p>
      <p>p2</p>
      <p>p3</p>
      <p>p4</p>
      <p>
        p5
        <img
          src="./imgs/loading.gif"
          data-src="./imgs/2.jpg"
          height="200px"
          alt=""
        />
      </p>
      <p>
        p6

        <img src="./imgs/3.jpg" width="300px" alt="" />
      </p>
      <p>p7</p>
      <p>
        p8

        <img
          src="./imgs/loading.gif"
          data-src="./imgs/3.jpg"
          height="200px"
          alt=""
        />
      </p>
    </div>
    <script>
      /*
        图片懒加载
        1. 获取所有data-src图片
        2. 循环判断每一张图片是否在可视区域
        3. 如果在可视区域src中的地址替换未data-src，并删除掉data-src
      */

      function lazyImg() {
        const imgs = document.querySelectorAll("img[data-src]");
        imgs.forEach((el) => {
          // 获取节点位置坐标
          const { top } = el.getBoundingClientRect();
          if (top < window.innerHeight - el.offsetHeight) {
            el.src = el.dataset.src;
            el.removeAttribute("data-src");
          }
        });
      }

      lazyImg();

      window.onscroll = function () {
        // 判断是否触底
        const dis =
          document.documentElement.scrollHeight -
          window.innerHeight -
          window.pageYOffset;
        // 触底
        if (dis <= 60) {
          // 创建新内容
          const newP = document.createElement("p");
          newP.innerHTML = "new P";
          box.append(newP);
        }

        // 当滚动高度>窗口高度的时候，显示top
        if (window.pageYOffset > window.innerHeight) {
          boxTop.style.display = "flex";
        } else {
          boxTop.style.display = "none";
        }

        // 图片懒加载
        lazyImg();
      };
      boxTop.onclick = function () {
        window.scrollTo({
          left: 0,
          top: 0,
          behavior: "smooth",
        });
      };
    </script>
  </body>
</html>
